package edu.xidian.bdilab.jrbigdata.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 阿里云发送短信工具类
 * Copyright: Copyright (c) 2021  zteits
 *
 * @ClassName: MessageUtil.java
 * @Description:
 * @version: v1.0.0
 * @author: wangfei
 * @date: 2019年9月25日   上午10:59:49
 * Modification History:
 * Date         Author          Version      Description
 * ---------------------------------------------------------*
 * 2019年9月25日      wangfs          v1.0.0          创建
 */
public class MessageUtil {

    private static final Logger logger = LoggerFactory.getLogger(MessageUtil.class);

    /**
     * 阿里云短信辅助
     * @param value
     * @return
     * @throws Exception
     */
    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    /**
     * 阿里云短信签名
     * @param accessSecret
     * @param stringToSign
     * @return
     * @throws Exception
     */
    @SuppressWarnings("restriction")
	public static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }






    /**
     * 阿里云平台-会员卡到期提醒短信
     * @param userPhone
     * @par
     * @return
     * @throws Exception
     */
    public static CommonResponse aliyunsendSms(String accessKeyId, String accessSecret, String userPhone,  String smsTitle, String templateCode, Map<String,String> content)  {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);


        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-beijing");
        request.putQueryParameter("PhoneNumbers", userPhone);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("SignName", smsTitle);

        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(content));


        try {
            CommonResponse response  = client.getCommonResponse(request);
            System.out.println(response.getData());
            return  response;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**第一种方法:
     * 建议使用
     */
    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }




    public static void main(String[] args) {
    final String app_id = "LTAI5tNhRQhVQxwmsVMFS8F6";
    final String app_secret = "MjIPnatg0tMkiFGOnwrvquH05ntAuk";
    final String signName = "慧诺德科技";
    final String templateCode = "SMS_217255048";
    String userPhone ="18633483823";
    Map<String,String> param = new HashMap<>();
    param.put("code","202009");
        CommonResponse commonResponse = MessageUtil.aliyunsendSms(app_id,
                app_secret,userPhone, signName,templateCode, param);
    JSONObject json = JSONObject.parseObject(commonResponse.getData());

     String code =(String)json.get("Code");
     String message =(String)json.get("Message");
    String requestId =(String)json.get("RequestId");
        System.out.print(JSONObject.toJSON(commonResponse));

}
}
